import 'package:flutter/material.dart';
import 'package:provider/provider.dart';


/// provider基本使用
class ProviderDemoHome extends StatefulWidget {
  const ProviderDemoHome({Key? key}) : super(key: key);

  @override
  _ProviderDemoHomeState createState() => _ProviderDemoHomeState();
}

class _ProviderDemoHomeState extends State<ProviderDemoHome> {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => ProviderModel(),
        )
      ],
      child: Scaffold(
        appBar: AppBar(
          title: LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
              var model = Provider.of<ProviderModel>(context);
              return Text("Provider ${model.count.toString()}");
            },
          ),
        ),
        body: CounterWidget(),
      ),
    );
  }
}

class CounterWidget extends StatelessWidget {
  const CounterWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<ProviderModel>(
      builder: (context, model, child) {
        return Column(
          children: [
            Expanded(
                child: Center(
              child: Text(
                model.count.toString(),
                style: TextStyle(fontSize: 32),
              ),
            )),
            Center(
              child: FlatButton(
                onPressed: () {
                  model.increment();
                },
                color: Colors.blue,
                child: Text(
                  "+",
                  style: Theme.of(context).textTheme.headline6,
                ),
              ),
            ),
            SizedBox(
              height: 15,
            )
          ],
        );
      },
    );
  }
}

/// ProviderModel 是ChangeNotifier的扩展类，用于调用notifyListener()方法后进行广播
class ProviderModel extends ChangeNotifier {
  int _count = 0;

  int get count => _count;

  void increment() {
    _count++;
    notifyListeners();
  }
}
